package org.smart4j.framework.helper;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.CollectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author Jungle
 * @created 2017/5/21 21:25
 */
public class IOCHelper {
	static {
		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
		if(MapUtils.isNotEmpty(beanMap)){
			for(Map.Entry<Class<?>,Object> beanEntry:beanMap.entrySet()){
				Class<?> beanClass = beanEntry.getKey();
				Object beanInstance = beanEntry.getValue();
				Field[] fields = beanClass.getDeclaredFields();
				if(ArrayUtils.isNotEmpty(fields)){
					for(Field beanField:fields){
						if(beanField.isAnnotationPresent(Inject.class)){
							Class<?> type = beanField.getType();
							Object o = beanMap.get(type);
							if(o!=null){
								ReflectionUtil.setField(beanInstance,beanField,o);
							}
						}
					}
				}
			}
		}
	}
}
